package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.admin.DevicePolicyManager;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.RepeatBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.clock.WriteAlarmClock;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.entity.CLRepeatTable;
import com.mission.schedule.entity.LocateAllNoticeTable;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.service.ClockService;
import com.mission.schedule.service.DownNongLiService;
import com.mission.schedule.service.DownRepeatService;
import com.mission.schedule.service.ServerUtil;
import com.mission.schedule.service.UpLoadService;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.DateTimeHelper;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.RepeatDateUtils;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import cn.jpush.android.api.JPushInterface;

public class AlarmDialog extends BaseActivity implements OnClickListener,
        OnCompletionListener {
    private int id = 0;
    private String content = "";
    private String userid = "0";
    String time = "";
    // private ImageView iv_showdialog_set;
    private TextView tv_content, tv_finish, tv_after, tv_time;
    private Map<String, String> mMap = null;

    SharedPrefUtil sharedPrefUtil = null;

    Context context;
    App app = null;
    private WakeLock mWakelock;
    private KeyguardManager km;
    private KeyguardLock kl;
    String alarmType;
    String ringcode;
    String alarmSound;
    String morningstate;
    String nightstate;
    String before;
    String alltimestate;
    String ringstate;
    String displaytime;
    String postpone;
    String alarmSoundDesc;
    String isalarmtype;
    MediaPlayer mediaPlayer = null;
    String stateone = "";
    String statetwo = "";
    String dateone = "";
    String datetwo = "";
    private RelativeLayout mRelativeLayoutbackground;
    private String mWay;
    private int imgid[] = {R.mipmap.alarm_bg, R.mipmap.alarm_bg1,
            R.mipmap.alarm_bg2, R.mipmap.alarm_bg3, R.mipmap.alarm_bg4,
            R.mipmap.alarm_bg5, R.mipmap.alarm_bg6};

    boolean fag = true;

    @Override
    protected void setListener() {

    }

    @Override
    protected void setContentView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.alarm_dialog);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        fag = true;
        init();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        init();
    }

    @Override
    protected void setAdapter() {

    }

    ActivityManager1 activityManager;

    private void init() {
        context = this;
        acquiremWakeLock();
        activityManager = ActivityManager1.getInstance();
        activityManager.addActivities(this);
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        app = App.getDBcApplication();
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        userid = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        alarmType = getIntent().getStringExtra("alarmType");
        isalarmtype = getIntent().getStringExtra("isalarmtype");
        ringcode = getIntent().getStringExtra("ringcode");
        alarmSound = getIntent().getStringExtra("alarmSound");
        alarmSoundDesc = getIntent().getStringExtra("alarmSoundDesc");
        id = getIntent().getIntExtra("cdId", 0);
        morningstate = getIntent().getStringExtra("morningstate");
        nightstate = getIntent().getStringExtra("nightstate");
        time = getIntent().getStringExtra("alarmclocktime");
        before = getIntent().getStringExtra("before");
        content = getIntent().getStringExtra("content");
        alltimestate = getIntent().getStringExtra("alltimestate");
        // ringstate = getIntent().getStringExtra("ringstate");
        displaytime = getIntent().getStringExtra("displaytime");
        postpone = getIntent().getStringExtra("postpone");
        stateone = getIntent().getStringExtra("stateone");
        statetwo = getIntent().getStringExtra("statetwo");
        dateone = getIntent().getStringExtra("dateone");
        datetwo = getIntent().getStringExtra("datetwo");
        ringstate = sharedPrefUtil.getString(this, ShareFile.USERFILE, ShareFile.RINGSTATE, "0");
        mMap = app.getqueryschrepID(id);
        mRelativeLayoutbackground = findViewById(R.id.alarm_dialog_background_img);
        Calendar cd1 = Calendar.getInstance();
        cd1.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        cd1.setTime(DateUtil.parseDateTime(time));
//        cd1.set(Calendar.MINUTE, Integer.parseInt(before));
        // SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        mWay = String.valueOf(cd1.get(Calendar.DAY_OF_WEEK));
        int idurl = Integer.valueOf(mWay);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = getResources().openRawResource(imgid[idurl - 1]);
        Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
        BitmapDrawable bd = new BitmapDrawable(getResources(), bm);
        mRelativeLayoutbackground.setBackgroundDrawable(bd);
        String weekstring = "";
        if (mWay.equals("1")) {
            weekstring = "星期天";
        } else if (mWay.equals("2")) {
            weekstring = "星期一";
        } else if (mWay.equals("3")) {
            weekstring = "星期二";
        } else if (mWay.equals("4")) {
            weekstring = "星期三";
        } else if (mWay.equals("5")) {
            weekstring = "星期四";
        } else if (mWay.equals("6")) {
            weekstring = "星期五";
        } else if (mWay.equals("7")) {
            weekstring = "星期六";
        }
        String timenow = Stringadd(cd1.get(Calendar.MONTH) + 1) + "-"
                + Stringadd(cd1.get(Calendar.DATE)) + "  "
                + Stringadd(cd1.get(Calendar.HOUR_OF_DAY)) + ":"
                + Stringadd(cd1.get(Calendar.MINUTE)) + "  " + weekstring;
        tv_content = findViewById(R.id.tv_content);
        tv_content.setText(content);
        tv_finish = findViewById(R.id.tv_finish);
        tv_finish.setOnClickListener(this);
        tv_after = findViewById(R.id.tv_after);
        tv_after.setOnClickListener(this);
        tv_time = findViewById(R.id.tv_time);
        if (ringstate.equals("0")) {
            Alarm(0);
        } else if (ringstate.equals("1")) {
            WriteAlarmClock.writeAlarm(getApplicationContext());
        } else if (ringstate.equals("2")) {
            ringcode = "g_220";
            alarmSound = "g_220";
            Alarm(2);
        } else if (ringstate.equals("3")) {
            Alarm(3);
        }
        tv_time.setText(timenow);

        if (!"0".equals(mMap.get(LocateAllNoticeTable.repID))) {
            Map<String, String> maprepeat = App.getDBcApplication().QueryhongFuData(mMap.get(LocateAllNoticeTable.repID));
            if (maprepeat != null) {
                if ("0".equals(maprepeat.get(CLRepeatTable.repInSTable)) && "0".equals(maprepeat.get(CLRepeatTable.repIsPuase))) {
                    if (app.queryChildRepeatIsSave(maprepeat.get(CLRepeatTable.repContent), maprepeat.get(CLRepeatTable.repNextCreatedTime), maprepeat.get(CLRepeatTable.repID)) == false) {
                        RepeatBean bean = null;
                        if ("1".equals(maprepeat.get(CLRepeatTable.repType))) {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 1, "", "");
                        } else if ("2".equals(maprepeat.get(CLRepeatTable.repType))) {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 2,
                                    maprepeat.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "");
                        } else if ("3".equals(maprepeat.get(CLRepeatTable.repType))) {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 3,
                                    maprepeat.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "");
                        } else if ("4".equals(maprepeat.get(CLRepeatTable.repType))) {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 4,
                                    maprepeat.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "0");
                        } else if ("6".equals(maprepeat.get(CLRepeatTable.repType))) {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 4,
                                    maprepeat.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\\", "").replace("\\", "").replace("\"", ""), "1");
                        } else {
                            bean = RepeatDateUtils.saveCalendar(maprepeat.get(CLRepeatTable.repTime), 5, "", "");
                        }
                        if (bean != null) {
//                            app.updateRepeatTimeNextDate(maprepeat.get(CLRepeatTable.repID), bean.repNextCreatedTime);
                            DownRepeatService.CreateRepeatSchNextData(maprepeat);
                        }
                    }
                    initDate();
                }
            }
        }
//        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//        Bundle extras = new Bundle();
//        intentappwidget.putExtras(extras);
//        sendBroadcast(intentappwidget);
    }


    List<Map<String, String>> repeatlist = new ArrayList<Map<String, String>>();
    Map<String, String> map;

    public void CheckCreateRepeatSchData() {
        repeatlist = app.QueryAllChongFuData(3);
        Log.e("TAG", "AlarmDialogCheckCreateRepeatSchData-start" + repeatlist.size());
        for (int i = 0; i < repeatlist.size(); i++) {
            map = repeatlist.get(i);

            Date nextDate = DateUtil.parseDateTime(map.get(CLRepeatTable.repNextCreatedTime).replace("T", " "));
            Date nowDate = DateUtil.parseDateTime(DateUtil.formatDateTime(new Date()));
            if (nextDate.compareTo(nowDate) == -1) {
                //补充子记事
                if ("0".equals(map.get(CLRepeatTable.repInSTable)) && "0".equals(map.get(CLRepeatTable.repIsPuase))) {
                    if (app.queryChildRepeatIsSave(map.get(CLRepeatTable.repContent), map.get(CLRepeatTable.repNextCreatedTime), map.get(CLRepeatTable.repID)) == false) {
                        DownRepeatService.CreateRepeatSchNextData(map);
                    }
                }
            }
        }
        QueryAlarmData.writeAlarm(this);

        Log.e("TAG", "AlarmDialogCheckCreateRepeatSchData-end");
    }

    private String Stringadd(int num) {
        String stringnum = num + "";
        if (stringnum.length() == 1) {
            stringnum = "0" + stringnum;
        }
        return stringnum;
    }

    private Vibrator vibrator;

    private void Alarm(int type) {
        try {
            Calendar cd = Calendar.getInstance();
            cd.setTime(DateUtil.parseDateTime(time));
            cd.add(Calendar.MINUTE, -Integer.parseInt(before));
            AssetFileDescriptor fileDescriptor = null;
            if ("3".equals(isalarmtype)) {
                if (DateTimeHelper.formatDateTimetoString(cd.getTime(), DateTimeHelper.FMT_yyyyMMddHHmm).equals(
                        DateTimeHelper.formatDateTimetoString(new Date(), DateTimeHelper.FMT_yyyyMMddHHmm))) {
                    fileDescriptor = getApplication().getAssets().openFd(ringcode + ".mp3");
                } else {
                    fileDescriptor = getApplication().getAssets().openFd(alarmSound + ".mp3");
                }
            } else if ("2".equals(isalarmtype)) {
                if (DateTimeHelper.formatDateTimetoString(cd.getTime(), DateTimeHelper.FMT_yyyyMMddHHmm).equals(
                        DateTimeHelper.formatDateTimetoString(new Date(), DateTimeHelper.FMT_yyyyMMddHHmm))) {
                    fileDescriptor = getApplication().getAssets().openFd(ringcode + ".mp3");
                } else {
                    fileDescriptor = null;
                }
            } else if ("0".equals(isalarmtype)) {
                fileDescriptor = null;
            } else {
                if (id < 0) {
                    if (id == -1) {
                        if ("0".equals(morningstate)) {
                            fileDescriptor = getApplication().getAssets().openFd(alarmSound);
                        }
                    } else if (id == -2) {
                        if ("0".equals(nightstate)) {
                            fileDescriptor = getApplication().getAssets().openFd(alarmSound);
                        }
                    } else {
                        fileDescriptor = getApplication().getAssets().openFd(alarmSound + ".mp3");
                    }
                } else {
                    fileDescriptor = getApplication().getAssets().openFd(alarmSound + ".mp3");
                }
            }
            if (fileDescriptor == null) return;
            if (type == 3) {
                long[] pattern = {100, 400}; // 停止 开启 停止 开启
                vibrator.vibrate(pattern, -1); // 重复两次上面的pattern
            } else {
                mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//STREAM_ALARM
                mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (fag) {
            WriteAlarmClock.writeAlarm(getApplicationContext());// 写入闹钟MainActivity.allContext
            fag = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_finish:
                if (null != mMap && mMap.size() > 0) {
                    writeCloseBase(mMap);
                }
                Intent intentac = new Intent(this, MainActivity.class);
                startActivity(intentac);

                Intent intent = new Intent(Const.SHUAXINDATA);
                intent.putExtra("data", "success");
                intent.putExtra("index", 1);
                intent.putExtra("what", 2);
                context.sendBroadcast(intent);

                this.finish();
                break;
            case R.id.tv_after:
                if (isBackground(context) == true) {
                    final Window win = getWindow();
                    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                            | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
                    initDate();
                    WriteAlarmClock.writeAlarm(getApplicationContext());
                    activityManager.doAllActivityFinish();
                } else {
                    this.finish();
                }

                break;
            default:
                break;
        }
    }

    // ==========================闹钟=======================================//
    private void initDate() {
        if (ServerUtil.isServiceRunning(context, "com.mission.schedule.service.ClockService") == false) {
            Intent intent = new Intent(this, ClockService.class);
            intent.setAction("com.mission.schedule.service.ClockService");
            intent.setPackage(getPackageName());
            intent.putExtra("WriteAlarmClockwrite", "0");
            startService(intent);
        }
    }

    private void writeCloseBase(Map<String, String> mMap) {
        updateSchedule(mMap, ScheduleTable.schIsEnd, ScheduleTable.schUpdateState);
        updateSchClock(mMap, LocateAllNoticeTable.isEnd);

        this.finish();
    }

    @Override
    public boolean onKeyDown(int kCode, KeyEvent kEvent) {
        if (kCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return super.onKeyDown(kCode, kEvent);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        releasemWakeLock();
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mRelativeLayoutbackground.setBackgroundDrawable(null);
        if (fag) {
            WriteAlarmClock.writeAlarm(getApplicationContext());// 写入闹钟MainActivity.allContext
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (DateUtil.formatDate(new Date()).equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME, DateUtil.formatDate(new Date())))) {
            updateLoginDate();
        } else {
            if (!DateUtil.formatDate(new Date()).equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date())))) {
                sharedPrefUtil.putString(this, ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, "");
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date()));
                updateLoginDate();
            }
        }
    }


    //上传每天第一次打开信息
    private void updateLoginDate() {
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (!userid.substring(0, 1).equals("-")) {
                String path = URLConstants.更新用户最后登录时间 + userid + "&userOpenId=1&version=" + getVersion() + "&phoneType="
                        + android.os.Build.MANUFACTURER + "-" + android.os.Build.MODEL.replace(" ", "");
                StringRequest request = new StringRequest(Request.Method.GET, path,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String s) {
                                if (!TextUtils.isEmpty(s)) {
                                    try {
                                        Gson gson = new Gson();
                                        SuccessOrFailBean bean = gson.fromJson(s, SuccessOrFailBean.class);
                                        if (bean.status == 0) {
                                            sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.ENDLOGINDATE, DateUtil.formatDate(new Date()));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {

                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        } else {
            int sid = Math.abs(Integer.valueOf(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0")));
            String path = URLConstants.新游客试用 + "?phoneType=" + android.os.Build.MODEL.replace(" ", "") + "&id=" + sid + "&version=" + getVersion() + "&pushMac=" + JPushInterface.getRegistrationID(context);
            StringRequest request = new StringRequest(Request.Method.GET, path,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String result) {

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            request.setTag("resgin");
            request.setRetryPolicy(new DefaultRetryPolicy(3000, 1, 1.0f));
            App.getHttpQueues().add(request);
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return "V" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "V6.3.2";
        }
    }

    private void acquiremWakeLock() {
        if (mWakelock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");// SCREEN_DIM_WAKE_LOCK bright WAKE
            mWakelock.acquire();
        }
        km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");
        // 解锁
        kl.disableKeyguard();
    }

    private void releasemWakeLock() {
        kl.reenableKeyguard();
        if (mWakelock != null && mWakelock.isHeld()) {
            mWakelock.release();
            mWakelock = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    private void updateSchedule(Map<String, String> mMap, String key, String key1) {
        String value;
        String key2 = "";
        Map<String, String> upMap = new HashMap<String, String>();
        if (key.equals("schIsEnd")) {
            key2 = "isEnd";
        }
        if ("0".equals(mMap.get(key2))) value = "1";
        else value = "0";
        upMap.put(key, value);
        upMap.put(key1, "2");
        App.getDBcApplication().updateScheduleData(upMap, "where schID=" + mMap.get(LocateAllNoticeTable.schID));
        mMap.put(key, value);
    }

    private void updateSchClock(Map<String, String> mMap, String key) {
        try {
            String value = "0";
            Map<String, String> upMap = new HashMap<String, String>();
            if ("0".equals(mMap.get(key))) value = "1";
            else value = "0";
            upMap.put(key, value);
            App.getDBcApplication().updateSchIsEnd(upMap, "where schID=" + mMap.get("schID"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {// 监听播放器放完
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        releasemWakeLock();
    }


    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace =" + appProcess.importance + ",context.getClass().getName()=" + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台" + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台" + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }
}
